var standardConfig = function () {
    var maxLevel = 4;
    var levelBit = 3;
    var opItemValue = '1';
    var configTable = '.standard-config-table';
    var configTableId = '#standard-config';
    var editable = true;

    function eventHandler() {
        $(document).off('mouseover', '.move-step > .btn');
        $(document).on('mouseover', '.move-step > .btn', hoverMoveStepBtn);
        $(document).off('mouseleave', '.move-step > .btn');
        $(document).on('mouseleave', '.move-step > .btn', leaveMoveStepBtn);

        $(document).off('click', '.add-btn-menu > .dropdown-item');
        $(document).on('click', '.add-btn-menu > .dropdown-item', addStepHandle);

        $(document).off('click', '.move-step > .btn');
        $(document).on('click', '.move-step > .btn', moveStepHandle);

        $(document).off('click', '.k-portlet__head-toolbar .remove-all');
        $(document).on('click', '.k-portlet__head-toolbar .remove-all', removeStepHandle);

        //解决合并单元格hover效果
        $(document).off('mouseover', configTable + ' tbody tr > td.merge-cell-td');
        $(document).on('mouseover', configTable + ' tbody tr > td.merge-cell-td', mouseOverRow);
        $(document).off('mouseout', configTable + ' tbody tr > td.merge-cell-td');
        $(document).on('mouseout', configTable + ' tbody tr > td.merge-cell-td', mouseOutRow);

        //复选框联动选择及其效果
        $(document).off('change', configTable + ' .table [name="btSelectItem"]');
        $(document).on('change', configTable + ' .table [name="btSelectItem"]', onChangeSelect);
        $(document).off('change', configTable + ' .table [name="btSelectAll"]');
        $(document).on('change', configTable + ' .table [name="btSelectAll"]', onChangeSelectAll);

        $(document).off('change', 'input[name="isImport"]');
        $(document).on('change', 'input[name="isimport"]', onChangeImportant);

        $(document).off('click', configTable + ' .switch-icon-btn');
        $(document).on('click', configTable + ' .switch-icon-btn', toggleJobRequirements);

        /*
        $(document).off('click', '.btn.version-contrast');
        $(document).on('click', '.btn.version-contrast', versionContrast);
        */

        //*****数据项配置--开始*****//
        $(document).off('show.bs.modal', '#data-item-config');
        $(document).on('show.bs.modal', '#data-item-config', initDataItemConfig);

        for (var level = 1; level <= maxLevel; level++) {
            $(document).off('click', '.add-step-' + level);
            $(document).off('click', '.delete-step-' + level);
            $(document).on('click', '.add-step-' + level, addStepDataItem);
            $(document).on('click', '.delete-step-' + level, deleteStepDataItem);
        }

        $(document).off('change', '.data-option-type');
        $(document).on('change', '.data-option-type', switchDataOptionType);

        $(document).off('click', '.add-checkbox-name');
        $(document).on('click', '.add-checkbox-name', addCheckboxInput);

        $(document).off('click', '.add-radio-name');
        $(document).on('click', '.add-radio-name', addRadioInput);

        $(document).off('click', '.data-item-config .k-input-icon > .k-input-icon__icon');
        $(document).on('click', '.data-item-config .k-input-icon > .k-input-icon__icon', function () {
            $(this).parents('.col-md-12.clearfix:first').remove();
        });

        $(document).off('click', '.data-item-config .confirm-btn');
        $(document).on('click', '.data-item-config .confirm-btn', confirmDataItem);
        //*****数据项配置--结束*****//

    }

    /**
     * 鼠标移动到上移下移按钮的事件处理
     */
    function hoverMoveStepBtn(e) {
        if ($(e.target).hasClass('btn-describe')) {
            return;
        }
        $(this).children('.btn-describe').removeClass('fadeOutLeft').addClass('fadeInLeft');
        $(this).children('.btn-describe').show();
    }

    /**
     * 鼠标离开到上移下移按钮的事件处理
     */
    function leaveMoveStepBtn() {
        $(this).children('.btn-describe').removeClass('fadeInLeft').addClass('fadeOutLeft');
        $(this).children('.btn-describe').hide();
    }

    /**
     * 定位到指定行
     * @param $row
     */
    function scrollToRow($row) {
        var viewPort = KUtil.getViewPort();
        var documentTop = document.documentElement.scrollTop;
        var documentBottom = documentTop + viewPort.height;
        var scrollTop = $row.offset().top;
        var rowspan = parseInt($row.children('td.merge-cell-td:first').attr('rowspan') || 1);

        //当前行已经可见，那么不做跳转
        if (scrollTop > documentTop
            && scrollTop + 65 * rowspan < documentBottom) {
            return;
        }

        KUtil.scrollTop(scrollTop, 500);
    }
    
    /**
     * 创建新行
     */
    function addStepHandle() {
        var $table = $(configTableId);
        var classifyName = $(this).data('classifyName');
        var indexObj = getNewRowIndex($table, classifyName);
        var row =  createNewRowData($table, classifyName, indexObj);
        $table.bootstrapTable('insertRow', {index: indexObj.index , row: row});
        if (indexObj.mergeData) {
            updateClassifyValue($table, indexObj);
        }

        var tableDataRows = $table.bootstrapTable('getData');
        $table.bootstrapTable('load', tableDataRows);
        KBsTExt.recastBtSelect($table);
        KBsTExt.mergeCells($table);

        //选中当前插入行
        var insertColIndex = indexObj.mergeData ? indexObj.mergeData.colIndex : 1;
        var $insertRow = $table.children('tbody').children('tr:eq('+ indexObj.index +')');
        var $checkbox = $insertRow.find('td:eq('+ insertColIndex +') [name="btSelectItem"]:first');
        $checkbox.click();

        scrollToRow($insertRow);
    }

    /**
     * 重置行数据
     * @param newRow
     * @param prop
     * @param row
     * @returns {*}
     */
    function resetRowData(newRow, row, prop) {
        if (typeof row[prop] === 'number') {
            if (prop.match('Classify')) {
                newRow[prop] = row[prop];
            } else {
                newRow[prop] = 0;
            }
        } else if (typeof row[prop] === 'boolean') {
            newRow[prop] = false;
        } else if (typeof row[prop] === 'string') {
            newRow[prop] = "";
        } else if (Array.isArray(row[prop])) {
            newRow[prop] = [];
        } else {
            newRow[prop] = null;
        }

        return newRow;
    }

    /**
     * 获取新增行的索引
     * @param $table
     * @param classifyName
     * @returns {*}
     */
    function getNewRowIndex($table, classifyName) {
        var lastAreaRow;
        var mergeData;
        var tableDataRows = $table.bootstrapTable('getData');
        var selectRows = getSelectRows($table, classifyName);
        var lastStep;
        var index = tableDataRows.length;
        var stepLength = selectRows.length;
        if (stepLength > 0) {
            lastStep = selectRows[stepLength - 1];
            mergeData = lastStep.mergeData;
            index = mergeData.rowIndex + mergeData.count;
        }

        return {
            index: index,
            mergeData: mergeData
        };
    }

    /**
     * 创建新行空数据
     * @param $table
     * @param classifyName
      * @param indexObj
     * @returns {{}}
     */
    function createNewRowData($table, classifyName, indexObj) {
        var tableDataRows = $table.bootstrapTable('getData');
        var options = $table.bootstrapTable('getOptions');
        var newRow = {};
        var lastRow = tableDataRows[indexObj.index - 1];
        if (lastRow) {
            for (var prop in lastRow) {
                if (lastRow.hasOwnProperty(prop)) {
                    if (prop === classifyName + 'Classify') {
                        newRow[prop] = lastRow[prop] + 1;
                    } else if (prop === 'numClassify' || prop === 'num') {
                        if (classifyName === 'areaName') {
                            newRow[prop] = lastRow[prop] + 1;
                        } else {
                            newRow[prop] = lastRow[prop];
                        }
                    } else {
                        resetRowData(newRow, lastRow, prop);
                    }
                }
            }
        } else {
            newRow = {
                "num": 1,
                "areaName": "",
                "checkItem": "",
                "stepId": "",
                "stepName": "",
                "isImportant": 1,
                "refPicture": [],
                // "refAr": "",
                "dataItem": [],
                "hasPic": 1,
                "rfid": 1,
                "stepRemark": 1,
                "executeTime": 1
            }
        }

        newRow.stepId = 'stepId-' + new Date().getTime();
        return newRow;
    }

    /**
     * 更新插入行以下的分类值
     * @param $table
     * @param indexObj
     */
    function updateClassifyValue($table, indexObj) {
        var options = $table.bootstrapTable('getOptions');
        var tableData = $table.bootstrapTable('getData');

        var index = options.mergeFields.indexOf(indexObj.mergeData.classifyName);

        if (index < 0) {
            return;
        }

        tableData.forEach(function (item, i) {
            if (i > indexObj.index) {
                for (var j = index; j < options.mergeFields.length; j++) {
                    var classify = options.mergeFields[j] + 'Classify';
                    item[classify] ++;
                    if (options.mergeFields[j] === 'areaName') {
                        item.numClassify ++;
                        item.num = item.numClassify + 1;
                    }
                }
            }

            delete item.mergeData;
        });
    }

    /**
     * 删除表单数据
     * @param $table
     * @param rows
     */
    function removeRow($table, rows) {
        if (Array.isArray(rows)) {
            rows.forEach(function (row) {
                $table.bootstrapTable('removeByUniqueId', row.stepId);
            })
        } else {
            $table.bootstrapTable('removeByUniqueId', rows.stepId);
        }


        KBsTExt.recastBtSelect($table);
        KBsTExt.mergeCells($table);
        var tableData = $table.bootstrapTable('getData');
        tableData.forEach(function (row) {
            row.num = row.numClassify + 1;
        });
        $table.bootstrapTable('load', tableData);
    }

    /**
     *  操作列事件注册
     */
    var operateEvents = {
        'click .delete': function (e, value, row, index) {
            var $table = this.$el;
            swal({
                title: '确认？',
                text: "您确定要删除这条数据吗？",
                type: 'question',
                showCancelButton: true
            }).then(function(result) {
                if (result.value) {
                    removeRow($table, row);
                    swal("成功！", "该条数据删除成功!", "success");
                }
            });
        }
    };

    /**
     * 定制操作列
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function operateFormatter(value, row, index) {
        return  `<button type="button" class="btn btn-outline-dark btn-icon delete" title="删除">
                    <i class="la la-trash"></i>
                </button>`;
    }

    /**
     * 对表数据进行分类重组
     * @param $table
     * @param tableDataRows
     * @returns {Array}
     */
    function reformTableDataRows($table, tableDataRows) {
        var options = $table.bootstrapTable('getOptions');
        var tableData = [];
        var classifies = [];

        //获取分类数组
        options.mergeFields.forEach(function (field) {
            var classify = field + 'Classify';
            var classifyArr = [];
            tableDataRows.forEach(function (row) {
                if (row.hasOwnProperty(classify) &&
                    $.inArray(row[classify], classifyArr) === -1) {
                    classifyArr.push(row[classify]);
                }
            });

            classifies.push({
                classify:  classify,
                classifyArr: classifyArr
            });
        });

        if (classifies.length === 0) {
            tableData = [tableDataRows];
        } else {
            //对行数据进行分类
            classifies.forEach(function (item) {
                var classifyRows = [];
                item.classifyArr.forEach(function (classify) {
                    var classifyRow = [];
                    tableDataRows.forEach(function (row, index) {
                        if (row.hasOwnProperty(item.classify)
                            && row[item.classify] === classify) {
                            row.index = index;
                            classifyRow.push(row);
                        }
                    });
                    classifyRows.push(classifyRow);
                });
                tableData.push({
                    classify: item.classify,
                    classifyRows: classifyRows
                });
            });

            var classifyRows = [];
            tableDataRows.forEach(function (row) {
                classifyRows.push([row]);
            });
            tableData.push({
                classify: 'stepClassify',
                classifyRows: classifyRows
            });

            //对数据进行组装
            var newTableData = [];
            tableData.forEach(function (item, index) {
                if (index > 0) {
                    var newClassifyRows = [];
                    var lastClassifyRows = tableData[index - 1].classifyRows;
                    var indexes = [];
                    lastClassifyRows.forEach(function (lastClassifyRow) {
                        var newClassifyRow = [];
                        var count = 0;
                        item.classifyRows.forEach(function (classifyRow, j) {
                            if (indexes.indexOf(j) !== -1) {
                                return;
                            }
                            if (count < lastClassifyRow.length) {
                                newClassifyRow.push(classifyRow);
                                count += classifyRow.length || 1;
                                indexes.push(j);
                            }
                        });
                        newClassifyRows.push(newClassifyRow);
                    });

                    newTableData.push({
                        classify: item.classify,
                        classifyRows: newClassifyRows
                    });
                }
            });
        }

        if (newTableData.length > 0) {
            var firstClassifyRows = [];
            newTableData[0].classifyRows.forEach(function (classifyRows) {
                firstClassifyRows = firstClassifyRows.concat(classifyRows);
            });

            newTableData[0].classifyRows = [firstClassifyRows];
        }

        return newTableData;
    }

    /**
     * 获取行数据
     * @param $table
     * @param classifyName
     * @returns {Array}
     */
    function getSelectRows($table, classifyName) {
        var selectRows = [];
        var tableDataRows = $table.bootstrapTable('getData');
        var options = $table.bootstrapTable('getOptions');
        var $checkboxes = [];
        // 获取新增所需的行数据
        if (classifyName) {
            $checkboxes = $table.find('[name=btSelectItem][classify-name="'+ classifyName +'"]:checked');
            if ($checkboxes.length > 0) {
                $checkboxes.each(function (j, checkbox) {
                    var $selectTd = $(checkbox).parents('td:first');
                    var mergeData = $selectTd.data('mergeData');
                    var selectRow = tableDataRows[mergeData.rowIndex];
                    selectRow.mergeData = mergeData;
                    selectRows.push(selectRow);
                });
            } else {
                $table.find('tr').each(function (index, tr) {
                    var $bsCheckbox = $(tr).children('td.bs-checkbox:last');
                    var $checkbox = $bsCheckbox.find('[name=btSelectItem]:checked');
                    if ($checkbox && $checkbox.length > 0) {
                        var rowIndex = $(tr).index();
                        var selectRow = tableDataRows[rowIndex];
                        var classify = classifyName + 'Classify';
                        if (selectRow.hasOwnProperty(classify)) {
                            tableDataRows.some(function (row, index) {
                                if (row[classify] === selectRow[classify]) {
                                    rowIndex = index;
                                    selectRow = row;
                                    return true;
                                }
                            });

                            var $selectTr = $table.find('tr:eq('+ (rowIndex + 1)+')');
                            var $selectCheckbox = $selectTr.find('[classify-name="'+ classifyName +'"]');
                            var $selectTd = $selectCheckbox.parents('.bs-checkbox:first');
                            selectRow.mergeData = $selectTd.data('mergeData');
                        } else {
                            selectRow.mergeData = {
                                classifyName: classifyName,
                                rowIndex: rowIndex,
                                colIndex: $bsCheckbox.index(),
                                count: 1
                            };
                        }

                        selectRows.push(selectRow);
                    }
                });
            }
            // 获取移动行所需的行数据
        } else {
            options.mergeFields.some(function (field) {
                $checkboxes = $table.find('[name=btSelectItem][classify-name="'+ field +'"]:checked');
                var classifyRows = [];
                if ($checkboxes && $checkboxes.length > 0) {
                    $checkboxes.each(function (j, checkbox) {
                        var $selectTd = $(checkbox).parents('td:first');
                        var mergeData = $selectTd.data('mergeData');
                        var selectRow = tableDataRows[mergeData.rowIndex];
                        selectRow.mergeData = mergeData;
                        classifyRows.push(selectRow);
                    });
                }

                var classify = field + 'Classify';
                if (classifyRows.length > 0) {
                    selectRows = {
                        classify: classify,
                        classifyRows: classifyRows
                    };
                    return true;
                }
            });

            if (selectRows.length === 0) {
                var stepRows = [];
                $table.find('tr').each(function (index, tr) {
                    var $bsCheckbox = $(tr).children('td.bs-checkbox:last');
                    var $checkbox = $bsCheckbox.find('[name=btSelectItem]:checked');
                    if ($checkbox && $checkbox.length > 0) {
                        var rowIndex = $(tr).index();
                        var selectRow = tableDataRows[rowIndex];
                        selectRow.mergeData = {
                            rowIndex: rowIndex,
                            colIndex: $bsCheckbox.index(),
                            count: 1
                        };
                        stepRows.push(selectRow);
                    }
                });

                selectRows = {
                    classify: 'stepClassify',
                    classifyRows: stepRows
                };
            }
        }

        return selectRows;
    }

    /**
     * 交换分类行分类值
     * @param currentRows
     * @param nextRows
     * @param classify
     */
    function toggleClassify(currentRows, nextRows, classify) {
        currentRows.forEach(function (item) {
            item[classify] --;
            if (classify.match('areaName')) {
                item.numClassify --;
            }
            item.num = item.numClassify + 1;
        });
        nextRows.forEach(function (item) {
            item[classify]++;
            if (classify.match('areaName')) {
                item.numClassify ++;
            }
            item.num = item.numClassify + 1;
        });
    }

    /**
     * 上移选中分类的行数据
     * @param tableData
     * @param selectRows
     */
    function moveUpClassifyRows(tableData, selectRows) {
        var movedClassifyRows = [];
        tableData.some(function (item) {
            if (item.classify === selectRows.classify) {
                item.classifyRows.forEach(function (rows) {
                    var isCanMove = true;
                    rows.forEach(function (classifyRow, i) {
                        if (!isCanMove) {
                            return;
                        }
                        var isMoveAble = false;
                        if (Array.isArray(classifyRow)) {
                            isMoveAble = classifyRow.some(function (row) {
                                return selectRows.classifyRows.some(function (selectRow) {
                                    return row.index === selectRow.index;
                                });
                            });
                        }

                        if (isMoveAble) {
                            if (i === 0) {
                                isCanMove = false;
                            } else {
                                var tempRow = rows[i - 1];
                                rows[i - 1] = classifyRow;
                                rows[i] = tempRow;
                                toggleClassify(rows[i - 1], rows[i], selectRows.classify);
                            }
                        }
                    });
                });

                movedClassifyRows = item.classifyRows;
                return true;
            }
        });

        return movedClassifyRows;
    }

    /**
     * 下移选中分类的行数据
     * @param tableData
     * @param selectRows
     * @returns {*}
     */
    function moveDownClassifyRows(tableData, selectRows) {
        var movedClassifyRows = [];
        tableData.some(function (item) {
            if (item.classify === selectRows.classify) {
                item.classifyRows.forEach(function (rows) {
                    var isCanMove = true;
                    for (var i = rows.length - 1; i >= 0; i--) {
                        if (!isCanMove) {
                            return;
                        }
                        var isMoveAble = false;
                        var classifyRow = rows[i];
                        if (Array.isArray(classifyRow)) {
                            isMoveAble = classifyRow.some(function (row) {
                                return selectRows.classifyRows.some(function (selectRow) {
                                    return row.index === selectRow.index;
                                });
                            });
                        }

                        if (isMoveAble) {
                            if (i === rows.length - 1) {
                                isCanMove = false;
                            } else {
                                var tempRow = rows[i + 1];
                                rows[i + 1] = classifyRow;
                                rows[i] = tempRow;
                                toggleClassify(rows[i], rows[i + 1], selectRows.classify);
                            }
                        }
                    }
                });

                movedClassifyRows = item.classifyRows;
                return true;
            }
        });

        return movedClassifyRows;
    }

    /**
     * 上移步骤并返回重组后的行数据
     * @param tableData
     * @param selectRows
     * @param isMoveUp
     * @returns {Array}
     */
    function moveStep(tableData, selectRows, isMoveUp) {
        var movedClassifyRows = [];
        if (isMoveUp) {
            movedClassifyRows = moveUpClassifyRows(tableData, selectRows);
        } else {
            movedClassifyRows = moveDownClassifyRows(tableData, selectRows);
        }

        var reformRows = [];
        movedClassifyRows.forEach(function (classifyRow) {
            classifyRow.forEach(function (row) {
                reformRows = reformRows.concat(row)
            });
        });
        return reformRows;
    }

    /**
     * 恢复移动行选中状态
     * @param $table
     * @param selectRows
     * @param reformRows
     */
    function restoreCheckedRow($table, selectRows, reformRows) {
        reformRows.forEach(function (row, i) {
            var $selectRow = $table.children('tbody').children('tr:eq('+ i +')');
            if (typeof row.index === 'undefined') {
                return;
            }

            selectRows.classifyRows.forEach(function (selectRow) {
                if (row.index  === selectRow.index) {
                    var colIndex = selectRow.mergeData ? selectRow.mergeData.colIndex : 1;
                    var $checkbox = $selectRow.find('td:eq('+ colIndex +') [name="btSelectItem"]:first');
                    $checkbox.click();
                    scrollToRow($selectRow);
                }
            });
        });
    }

    /**
     * 鼠标点击上移/下移按钮的事件处理
     */
    function moveStepHandle() {
        var $table = $(this).parents('.edit-step-group').siblings('.bootstrap-table').find('table.table-hover');
        var tableDataRows = $table.bootstrapTable('getData');
        var tableData = reformTableDataRows($table, tableDataRows);
        var selectRows = getSelectRows($table);
        var reformRows = [];
        var isMoveUp = $(this).hasClass('step-up');
        reformRows = moveStep(tableData, selectRows, isMoveUp);
        if (reformRows.length === 0) {
            return;
        }

        $table.bootstrapTable('load', reformRows);
        KBsTExt.mergeCells($table);
        restoreCheckedRow($table, selectRows, reformRows);
    }

    /**
     * 批量删除步骤的事件处理
     */
    function removeStepHandle() {
        var $table = $(configTable + '  table.table-hover');
        var selectRows = getSelectRows($table);
        var tableDataRows = $table.bootstrapTable('getData');
        var removeRows = [];
        tableDataRows.forEach(function (row, index) {
            selectRows.classifyRows.forEach(function (classifyRow) {
                var mergeData = classifyRow.mergeData;
                if (index >= mergeData.rowIndex
                    && index < mergeData.rowIndex + mergeData.count) {
                    removeRows.push(row);
                }
            });
        });

        if (removeRows.length === 0) {
            return;
        }
        swal({
            title: '确认？',
            text: "您确定要删除所有步骤吗？",
            type: 'question',
            showCancelButton: true
        }).then(function(result) {
            if (result.value) {
                removeRow($table, removeRows);
                swal("成功！", "数据删除成功!", "success");
            }
        });
    }

    /**
     * 合并单元格hover效果
     * @param e
     */
    function mouseOverRow(e) {
        var $table = $(configTableId);
        var dataIndex = $(this).parent().data('index');
        var rowspan = $(this).attr('rowspan');
        if ($(this).hasClass('bs-checkbox')) {
            $(this).next().addClass('active');
        } else {
            $(this).prev().addClass('active');
        }

        if ($(this).index() === 1) {
            $(this).prev().addClass('active');
        }

        if ($(this).index() === 2) {
            $(this).prev().prev().addClass('active');
        }

        for (var i = 0; i < rowspan; i++) {
            var $activeTr = $table.find('tr[data-index='+ (i + dataIndex) +']');
            var colIndex = $(this).index();
            $activeTr.children('td').each(function (index, td) {
                if (index > colIndex) {
                    $(td).addClass('active');
                }
            });
            $activeTr.addClass('active');
        }
    }

    /**
     * 合并单元格out效果
     * @param e
     */
    function mouseOutRow(e) {
        var $table = $('#standard-config');
        var dataIndex = $(this).parent().data('index');
        var rowspan = $(this).attr('rowspan');
        if ($(this).hasClass('bs-checkbox')) {
            $(this).next().removeClass('active');
        } else {
            $(this).prev().removeClass('active');
        }

        if ($(this).index() === 1) {
            $(this).prev().removeClass('active');
        }

        if ($(this).index() === 2) {
            $(this).prev().prev().removeClass('active');
        }

        for (var i = 0; i < rowspan; i++) {
            var $activeTr = $table.find('tr[data-index='+ (i + dataIndex) +']');
            var colIndex = $(this).index();
            $activeTr.children('td').each(function (index, td) {
                if (index > colIndex) {
                    $(td).removeClass('active');
                }
            });
            $activeTr.removeClass('active');
        }
    }

    /**
     * 切换选择分类
     * @param $_this
     * @param $target
     */
    function toggleSelectClassify($_this, $target) {
        var $table = $('#operation-stage');
        var dataIndex = $_this.data('index');
        var rowspan = $target.attr('rowspan');
        var isSelectedClassify = $target.hasClass('selected');
        for (var i = 0; i < rowspan; i++) {
            var $selectClassify = $table.find('tr[data-index='+ (i + dataIndex) +']');
            var $mergeCellTd = $selectClassify.find('td.merge-cell-td');
            var $btCheckBox = $selectClassify.find('[name="btSelectItem"]');
            if (isSelectedClassify) {
                $selectClassify.removeClass('selected');
                $mergeCellTd.removeClass('selected');
            } else {
                $selectClassify.addClass('selected');
                $mergeCellTd.addClass('selected');
            }
            $btCheckBox.click();
        }
    }

    /**
     * 切换选择步骤
     * @param $_this
     */
    function toggleSelectStep($_this) {
        var $stepRowCheckBox = $_this.find('[name="btSelectItem"]:last');
        if ($_this.hasClass('selected')) {
            $_this.removeClass('selected');
        } else {
            $_this.addClass('selected');
        }
        $stepRowCheckBox.click();
    }

    /**
     * 选中行的状态处理
     * @param e
     */
    function onChangeSelect(e) {
        var isChecked = $(this).prop('checked');
        var $parentTd = $(this).parents('td:first');
        var $table = $(this).parents('.table.table-hover:first');
        var mergeData = $parentTd.data('mergeData');
        if (mergeData) {
            $table.find('tr').each(function (i, tr) {
                if (i <= mergeData.rowIndex ||
                    i > mergeData.rowIndex + mergeData.count) {
                    return;
                }

                $(tr).children('td').each(function (j, td) {
                    var $checkbox = $(td).find('[name="btSelectItem"]');
                    if (j < mergeData.colIndex) {
                        $checkbox.prop('checked', false);
                    } else {
                        $checkbox.prop('checked', isChecked);
                        $(td).toggleClass('selected', isChecked);
                        if ($(td).index() === 1) {
                            $(td).prev().toggleClass('selected', $(td).hasClass('selected'));
                        }
                    }
                });

                $(tr).toggleClass('selected', isChecked);
            });
        } else {
            var $parentTr = $(this).parents('tr:first');
            var colIndex = $parentTd.index();
            $parentTr.children('td').each(function (i, td) {
                var $checkbox = $(td).find('[name="btSelectItem"]');
                if (i < colIndex) {
                    $checkbox.prop('checked', false);
                } else {
                    $checkbox.prop('checked', isChecked);
                }
            });
        }
    }

    /**
     * 选中所有行的状态处理
     */
    function onChangeSelectAll() {
        var isChecked = $(this).prop('checked');
        var $table = $(this).parents('.table.table-hover:first');
        $table.find('tr > td').toggleClass('selected', isChecked);
    }

    /**
     * 参照图片的格式化方法
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function referenceFormatter(value, row, index) {
        var isDisabled = !row.refPicture || row.refPicture.length === 0 ? 'disabled' : '';
        return `<button type="button" 
                        data-job-requirement="refPicture" 
                        class="btn switch-icon-btn btn-metal btn-circle btn-sm btn-icon `+ isDisabled +`" 
                        title="参考图">
                    <i class="la la-image"></i>
                </button>`;
    }

    /**
     * AR参照的格式化方法
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function ARReferenceFormatter(value, row, index) {
        var isDisabled = !row.refAr || row.refAr.length === 0 ? 'disabled' : '';
        return `<button type="button" 
                        data-job-requirement="refAr" 
                        class="btn switch-icon-btn btn-danger btn-circle btn-sm btn-icon `+ isDisabled +`"  
                        title="参考AR">
                    <i class="la la-cc-amex"></i>
                </button>`;
    }

    /**
     * 是否重要的格式化方法
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function importantFormatter(value, row, index) {
        var isChecked = value === 1 ? 'checked="checked"': '';
        var isDisabled = editable ? '': 'disabled';
        return `<span class="k-switch k-switch--icon">
                    <label>
                        <input type="checkbox" `+ isChecked +` `+ isDisabled +` name="isImport">
                        <span></span>
                    </label>
                </span>`;
    }

    /**
     * 检查是否包含数据项
     * @param dataItem
     * @returns {boolean}
     */
    function checkDataItem(dataItem) {
        var hasDataItem = false;
        if (Array.isArray(dataItem) && dataItem.length > 0) {
            dataItem.some(function (item) {
                if (item.options.length > 0) {
                    hasDataItem = true;
                    return true;
                }
            })
        }

        return hasDataItem;
    }

    /**
     * 作业要求的格式化方法
     * @param value
     * @param row
     * @param index
     * @returns {string}
     */
    function requirementsFormatter(value, row, index) {
        var jobRequirements = '';
        //是否必须填数据项
        var isDisabledDataItem = checkDataItem(row.dataItem) ? '' : 'disabled';
        jobRequirements += `<button type="button" 
                                    data-job-requirement="dataItem" 
                                    class="btn switch-icon-btn btn-accent btn-circle btn-sm btn-icon `+ isDisabledDataItem +`"
                                    title="数据项">
                                <i class="flaticon-list"></i>
                            </button>`;

        //是否必须传图片
        var isDisabledHasPic = row.hasPic && row.hasPic === 1? '' : 'disabled';
        jobRequirements += `<button type="button" 
                                    data-job-requirement="hasPic" 
                                    class="btn switch-icon-btn btn-warning btn-circle btn-sm btn-icon `+ isDisabledHasPic +`"  
                                    title="图片">
                                <i class="la la-camera"></i>
                            </button>`;

        //是否必须扫描RFID
        var isDisabledFfid = row.rfid && row.rfid === 1? '' : 'disabled';
        jobRequirements += `<button type="button" 
                                    data-job-requirement="rfid" 
                                    class="btn switch-icon-btn btn-primary btn-circle btn-sm btn-icon `+ isDisabledFfid +`"  
                                    title="RFID">
                                <i class="la la-bullseye"></i>
                            </button>`;

        //是否必须填备注
        var isDisabledStepRemark = row.stepRemark && row.stepRemark === 1? '' : 'disabled';
        jobRequirements += `<button type="button" 
                                    data-job-requirement="stepRemark" 
                                    class="btn switch-icon-btn btn-success btn-circle btn-sm btn-icon `+ isDisabledStepRemark +`"  
                                    title="备注">
                                <i class="la la-edit"></i>
                            </button>`;

        //是否必须填执行时长
        var isDisabledExecuteTime = row.executeTime && row.executeTime === 1? '' : 'disabled';
        jobRequirements += `<button type="button" 
                                    data-job-requirement="executeTime" 
                                    class="btn switch-icon-btn btn-brand btn-circle btn-sm btn-icon `+ isDisabledExecuteTime +`"  
                                    title="执行时长">
                                <i class="la la-clock-o"></i>
                            </button>`;
        return jobRequirements;
    }

    /**
     * 初始化操作阶段表格
     * @param $table
     * @param options
     * @param options.editable 是否可编辑
     */
    function initConfigTable($table, options) {
        var _options = {};
        _options.editable = true;
        _options.pagination = false;
        _options.clickToSelect = false;
        _options.search = false;
        _options.sidePagination = 'client';
        _options.uniqueId = 'stepId';
        _options.mergeFields = ['num', 'areaName', 'checkItem'];
        _options.columns = [
            {
                field: 'num',
                title: '序号'
            }, {
                field: 'areaState',
                checkbox: true,
                visible: options.editable
            }, {
                field: 'areaName',
                title: '区域名称',
                editable: true,
                align: 'left'
            }, {
                field: 'checkState',
                checkbox: true,
                visible: options.editable
            }, {
                field: 'checkItem',
                title: '检查项',
                editable: true,
                align: 'left'
            },{
                field: 'state',
                checkbox: true,
                visible: options.editable
            }, {
                field: 'stepId',
                visible: false
            }, {
                field: 'stepName',
                title: '检查标准',
                editable: true,
                type: 'textarea',
                align: 'left'
            }, {
                field: 'refPicture',
                title: '参考图',
                formatter: referenceFormatter
            // }, {
            //     field: 'refAr',
            //     title: '参考AR',
            //     formatter: ARReferenceFormatter
            }, {
                field: 'isImportant',
                title: '是否重要步骤',
                formatter: importantFormatter
            }, {
                field: 'jobRequirements',
                title: '作业要求',
                formatter: requirementsFormatter
            }];

        _options = $.extend(true, _options, options);
        editable = _options.editable;

        if (_options.editable) {
            _options.columns.push({
                field: 'operation',
                title: '操作',
                events: operateEvents,
                formatter: operateFormatter
            });

            $('.standard-config-table').addClass('editable');
        }
        KBsTExt.init(_options, $table);
    }

    function versionContrast() {
        standardConfig.contrastData = {
            left: '巴黎警察枪杀华人刘少尧现场确实 有鱼\n 死者当晚饮酒\n央广网北京4月2日消息（记者焦莹）据中国之声《央广新闻》报道，\n据法国媒体报道，\n法国国家警察局监察总局日前分别对巴黎枪杀案死者家人和3名涉案警察进行了调查询问。\n此前，死者家人称“父亲手持剪刀做鱼”。\n检察署调查人员证实，案发现场确实有鱼，\n但是鱼放在冰箱里。\n司法机关的法医确认，死者在案发当晚喝了酒\n',
            right: '巴黎警察枪杀华人刘少尧现场确实 无鱼\n 死者当晚饮酒\n央广网北京4月2日消息（记者焦莹）据中国之声《央广新闻》报道，\n据法国媒体报道，\n法国国家警察局监察总局日前分别对巴黎枪杀案死者家人和3名涉案警察进行了调查询问。\n此前，死者家人称“父亲手持剪刀做鱼”。\n检察署调查人员证实，案发现场确实有鱼，\n但是鱼放在冰箱里。\n司法机关的法医确认，死者在案发当晚喝了酒\n',
        };
        // standardConfig.contrastData = {
        //     left: 'the quick red fox\njumped over the hairy dog\njumped over the hairy dig\n12345\n阿 布',
        //     right: 'the quick brown fox\njumped over the lazy dog\njumped over the hairy dox\n123456\n属 布',
        // };
        var url='/Universal-Portal-web-Src/html/业务体系维护/操作单元/版本对比.html';
        window.open(url, "_blank");
    }

    /**
     * 切换是否重要
     */
    function onChangeImportant() {
        var $table = $(this).parents('table.table-hover:first');
        var uniqueId = $(this).parents('tr:first').data('uniqueid');
        var currRow = $table.bootstrapTable('getRowByUniqueId', uniqueId);
        var isChecked = $(this).prop('checked');
        if (isChecked) {
            currRow.isImportant = 1;
        } else {
            currRow.isImportant = 0;
        }

        $table.bootstrapTable('updateByUniqueId', {id: uniqueId, row: currRow});
        KBsTExt.recastBtSelect($table);
        KBsTExt.mergeCells($table);
    }
    
    /**
     * 切换作业要求的五种类型的状态(包含参考图片需自定义事件绑定)
     */
    function toggleJobRequirements() {
        var $table = $(this).parents('table.table-hover:first');
        var uniqueId = $(this).parents('tr:first').data('uniqueid');
        var currRow = $table.bootstrapTable('getRowByUniqueId', uniqueId);
        var jobRequirement = $(this).data('jobRequirement');

        if ($(this).attr('data-job-requirement') === 'dataItem') {
            var $configModal = $('#data-item-config');
            $configModal.data('dataItem', currRow.dataItem);
            $configModal.data('relatedTarget', $(this));
            $configModal.modal('show');
            return;
        }

        if ($(this).hasClass('disabled')) {
            $(this).removeClass('disabled');
            if (jobRequirement === 'dataItem' ||
                jobRequirement === 'refPicture') {
                currRow[jobRequirement] = currRow[jobRequirement] || [];
                currRow[jobRequirement].push({});
            // } else if (jobRequirement === 'refAr') {
            //     currRow[jobRequirement] = UUID.generate();
            } else {
                currRow[jobRequirement] = 1;
            }
        } else {
            $(this).addClass('disabled');
            if (jobRequirement === 'dataItem' ||
                jobRequirement === 'refPicture') {
                // currRow[jobRequirement] = [];
            // } else if (jobRequirement === 'refAr') {
            //     currRow[jobRequirement] = '';
            } else {
                currRow[jobRequirement] = 0;
            }
        }

        $table.bootstrapTable('updateByUniqueId', {id: uniqueId, row: currRow});
        KBsTExt.recastBtSelect($table);
        KBsTExt.mergeCells($table);
    }

    /**
     * 岗位标准配置表单验证
     * @param callback
     */
    function validateConfigForm(callback) {
        var $validateForm = $('form.standard-config-form');
        $validateForm.validate({
            // define validation rules
            rules: {
                orgId: {
                    required: true
                },
                postName: {
                    required: true
                },
                standardType: {
                    required: true
                },
                standardName: {
                    required: true
                },
                areaNames: {
                    required: true
                },
                areaName: {
                    required: true
                },
                checkItem: {
                    required: true
                },
                stepName: {
                    required: true
                }
            },
            messages: {
                orgId: {
                    required: '请选择所属组织!'
                },
                postName: {
                    required: '请选择岗位名称!'
                },
                standardType: {
                    required: '请选择标准类型!'
                },
                standardName: {
                    required: '请输入标准名称!'
                },
                areaNames: {
                    required: '请选择所属区域!'
                },
                areaName: {
                    required: '请输入区域名称!'
                },
                checkItem: {
                    required: '请输入检查项!'
                },
                stepName: {
                    required: '请输入检查标准!'
                }
            },

            //display error alert on form submit
            invalidHandler: function(event, validator) {
                if (validator.errorList.length > 0) {
                    $(validator.errorList[0].element).focus();
                }
            },

            submitHandler: callback
        });

        $validateForm.submit();
    }


    /**
     * 获取岗位标准配置数据
     * @param callback
     * @returns {*|jQuery}
     */
    function getConfigData(callback) {
        validateConfigForm(function () {
            var $table = $('#standard-config');
            var tableData = $table.bootstrapTable('getData');
            callback(tableData);
        });
    }

    //*****数据项配置--开始*****//

    /**
     * 根据数据组装步骤的数据项
     * @param $target
     * @param dataItem
     */
    function appendDataItem($target, dataItem) {
        var $dataItemContent = $target.find('#data-item .data-item-content');
        var dataItemForm = $(".edit-data-item-template").html();
        var dataItemTemplate = Handlebars.compile(dataItemForm);
        var dataItemHtml = dataItemTemplate(dataItem);
        $dataItemContent.html(dataItemHtml);

        dataItem.options.forEach(function (option) {
            var $dataLevelCode = $('[data-level-code="' + option.levelCode + '"]');
            $dataLevelCode.find('.data-type option[value="'+ option.dataType +'"]').prop('selected', true);
            $dataLevelCode.find('.data-option-type option[value="' + option.dataOptionType + '"]').prop('selected', true);
        });
    }

    /**
     * 根据数据组装步骤的数据集
     * @param $target
     * @param dataSetItem
     */
    function appendDataSet($target, dataSetItem) {
        var $tabPane = $target.find('#dataSet-select');
        var $dataItemContent = $tabPane.find('.data-item-content');

        var $dataSetInput = $tabPane.find('[name="dataSet"]');
        var dataSetIds = [];
        dataSetItem.forEach(function (item, index) {
            dataSetIds.push(item.dataItemId);
        });
        var nodesArray = KZtreeExt.parentNodes('dataSet-tree', dataSetIds);
        $dataSetInput.val(dataSetIds);
        $dataSetInput.data('pNodesId', nodesArray);

        var contexts = {};
        var templateHtml = $(".dataSet-select-template").html();
        var template = Handlebars.compile(templateHtml);
        contexts.dataSetItem = dataSetItem;
        $dataItemContent.html(template(contexts));
    }

    function initDataItemConfig() {
        var $configModal = $(this);
        var dataItem = $configModal.data('dataItem');
        if (!Array.isArray(dataItem) || dataItem.length === 0) {
            $configModal.find('.data-item-content').empty();
            return;
        }

        dataItem.forEach(function (item) {
            if (item.type === 'dataItem') {
                item.options.forEach(function (option, index) {
                    option.level = 1;
                    option.levelCode = autoPadZero(index + 1, levelBit);
                    option.isDataOptionType = !!option.dataOptionType;
                    option.isDataOptionType1 = option.dataOptionType === 1;
                    option.isDataOptionType2 = option.dataOptionType === 2;
                    option.isDataOptionType3 = option.dataOptionType === 3;
                    option.isDataOptionType4 = option.dataOptionType === 4;
                    if (option.radioBox) {
                        option.radioBox.forEach(function(radio, i) {
                            radio.levelCode = option.levelCode;
                            radio.index = i +1;
                        });
                    }
                    if (option.checkBox) {
                        option.checkBox.forEach(function(checkBox, i) {
                            checkBox.levelCode = option.levelCode;
                            checkBox.index = i +1;
                        });
                    }
                });

                appendDataItem($configModal, item);
            } else {
                appendDataSet($configModal, item.options);
            }
        });
    }

    /**
     * 获取已配置的数据项
     * @param $target
     * @returns {Array}
     */
    function getDataItems($target) {
        $target = $target || $('#data-item-config');
        var $tabPane = $target.find('.tab-pane');
        var dataItem = [];
        $tabPane.each(function (i, tabPane) {
            var paneId = $(tabPane).attr('id');
            var item = {
                type: 'dataItem',
                options: []
            };
            if (paneId === 'data-item') {
                $(tabPane).find('.step').each(function(j, step) {
                    var dataItemId = $(step).data('dataItemId');
                    var dataOptionName = $(step).find('[name="dataOptionName"]').val().trim();
                    var dataOptionType = $(step).find('[name="dataOptionType"]').val();
                    var option = {
                        dataItemId: dataItemId,
                        dataOptionName: dataOptionName,
                        dataOptionType: parseInt(dataOptionType)
                    };

                    if (dataOptionType === '2') {
                        option.radioBox = [];
                        $(step).find('[name="radioName"]').each(function(k, radio) {
                            option.radioBox.push({
                                radioName: $(radio).val().trim()
                            })
                        });
                    } else if (dataOptionType === '3') {
                        option.checkBox = [];
                        $(step).find('[name="checkName"]').each(function(l, check) {
                            option.checkBox.push({
                                checkName: $(check).val().trim()
                            })
                        });
                    }
                    item.options.push(option);
                });
            } else {
                item.type = 'dataSet';
                $(tabPane).find('.step').each(function(j, step) {
                    item.options.push({
                        dataItemId: $(step).data('dataItemId'),
                        entityId: $(step).find('[name="entityId"]').val(),
                        entityName: $(step).find('[name="entityName"]').val().trim(),
                        propertyId: $(step).find('[name="propertyId"]').val(),
                        propertyName: $(step).find('[name="propertyName"]').val().trim(),
                        minValue: $(step).find('[name="minValue"]').val().trim(),
                        maxValue: $(step).find('[name="maxValue"]').val().trim(),
                        propertyOpc: $(step).find('[name="propertyOpc"]').val().trim(),
                        propertyUnit: $(step).find('[name="propertyUnit"]').val().trim(),
                    });
                });
            }

            dataItem.push(item);
        });

        return dataItem;
    }

    /**
     * 数据项配置表单验证
     * @param $target
     * @param callback
     */
    function validateDataForm($target, callback) {
        var $validateForm = $target.find(".data-item-form:first");
        $.validator.addMethod("required-radioName", function(value, element) {
            var $radioBlock = $(element).parents('.radio-input-block');
            return !$radioBlock.hasClass('display-block') || value.trim() !== '';
        });
        $.validator.addMethod("required-checkName", function(value, element) {
            var $checkboxBlock = $(element).parents('.checkbox-input-block');
            return !$checkboxBlock.hasClass('display-block') || value.trim() !== '';
        });
        $validateForm.validate({
            // define validation rules
            rules: {
                dataOptionName: {
                    required: true
                },
                radioName: {
                    'required-radioName': true
                },
                checkName: {
                    'required-checkName': true
                }
            },
            messages: {
                dataOptionName: {
                    required: '输入数据项名称!'
                },
                radioName: {
                    'required-radioName': '请输入单选框名称!'
                },
                checkName: {
                    'required-checkName': '请输入复选框名称!'
                }
            },

            //display error alert on form submit
            invalidHandler: function(event, validator) {
                if (validator.errorList.length > 0) {
                    $(validator.errorList[0].element).focus();
                }
            },

            submitHandler: callback
        });

        $validateForm.submit();
    }

    /**
     * 步骤数据项配置的确定事件处理
     */
    function confirmDataItem() {
        var $configModal = $(this).parents('.modal');
        validateDataForm($configModal, function () {
            var $tabPane = $configModal.find('.tab-pane');
            var dataItem = getDataItems($configModal);
            var $relatedTarget = $configModal.data('relatedTarget');
            var $table = $relatedTarget.parents('table.table-hover:first');
            var uniqueId = $relatedTarget.parents('tr:first').data('uniqueid');
            var currRow = $table.bootstrapTable('getRowByUniqueId', uniqueId);
            if (checkDataItem(dataItem)) {
                $relatedTarget.removeClass('disabled');
            } else {
                $relatedTarget.addClass('disabled');
            }

            currRow.dataItem = dataItem;
            $table.bootstrapTable('updateByUniqueId', {id: uniqueId, row: currRow});
            KBsTExt.recastBtSelect($table);
            KBsTExt.mergeCells($table);
            $configModal.modal('hide');
        });
    }

    /**
     * 添加一个步骤数据项
     */
    function addStepDataItem() {
        var addBtnClass = $(this).attr('class');
        var level = parseInt(addBtnClass.substring(addBtnClass.length - 1, addBtnClass.length));
        var $parentsElement = $(this).parents('.tab-pane');
        var levelCode = getDataLevelCode(level, $(this));
        var stepStr = getDataOptionStr(level, levelCode, $parentsElement);
        if (level === 1) {
            $(this).parents('.data-item-form:first').find('.data-item-content').append(stepStr);
            var  $dataItemBox = $(this).parents('.add-step-data-block').siblings('.border');
            var  $dataItemContent_H = $dataItemBox.children().height();
            $dataItemBox.scrollTop($dataItemContent_H);
        } else {
            $(this).parents('.step-' + (level - 1)).find('.step-'+ (level - 1) +'-title').addClass('disabled-data-option');
            $(this).parents('.step-' + (level - 1)).find('.step-'+ (level - 1) +'-content').append(stepStr);
        }
    }

    function getDataLevelCode(level, $target) {
        var lastLevelCode = "";
        var $preStep = $target.parents('.step-' + (level - 1)).find('.step-'+ level +':last-child');
        if (level === 1) {
            $preStep = $target.parents('form').find('.step-1:last-child');
            if($preStep.length === 0) {
                return autoPadZero(1, levelBit);
            }
        } else {
            if ($preStep.length === 0) {
                return $target.parents('.step-' + (level - 1)).data('levelCode') + autoPadZero(1, levelBit);
            }
        }

        lastLevelCode = $preStep.data('levelCode');

        var lastLevelCodePre = lastLevelCode.substring(0, lastLevelCode.length - levelBit);
        var lastLevelCodeSuf = lastLevelCode.substring(lastLevelCode.length - levelBit, lastLevelCode.length);
        var levelCodeSuf = autoPadZero(parseInt(lastLevelCodeSuf) + 1, levelBit);
        return lastLevelCodePre + levelCodeSuf;
    }

    /**
     * 填充数据项模板
     * @param level
     * @param levelCode
     * @param $parentsElement
     * @returns {*}
     */
    function getDataOptionStr(level, levelCode, $parentsElement) {
        if (!level || level > 9) {
            return
        }
        var levelZh = ['', '', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        var contexts = {
            level: level,
            levelZh: levelZh[level],
            nextLevel: level + 1,
            nextLevelZh: levelZh[level + 1],
            levelCode: levelCode,
            isLevel1: level === 1,
            isMaxLevel: level !== maxLevel
        };

        var source = '';
        if($parentsElement.attr('id') === 'data-item'){
            source = $(".data-item-template").html();
        }

        var template = Handlebars.compile(source);
        return template(contexts);
    }

    function autoPadZero(num, n) {
        var len = num.toString().length;
        while(len < n) {
            num = "0" + num;
            len++;
        }
        return num;
    }

    function deleteStepDataItem() {
        var deleteBtnClass = $(this).attr('class');
        var level = parseInt(deleteBtnClass.substring(deleteBtnClass.length - 1, deleteBtnClass.length));

        var $disabledDataOption = $(this).parents('.step-' + (level - 1)).find('.disabled-data-option:first');
        if ($disabledDataOption.siblings('.step-'+ (level - 1) +'-content').children().length === 1) {
            $disabledDataOption.removeClass('disabled-data-option');
        }
        if ($(this).parents('.tab-pane').attr('id') === 'dataSet-select') {
            var input = $(this).parents('.data-item-form').find('.add-step-data-block input[type="hidden"]');
            var str = input.val();
            var dataSetIds = str.split(',');
            var thisId = $(this).attr('data-dataSetId');
            dataSetIds.splice(dataSetIds.indexOf(thisId), 1);
            input.val(dataSetIds);
        }
        $(this).parents('.step-' + level).remove();
    }

    /**
     * 切换数据项类型
     * @param e
     */
    function switchDataOptionType(e) {
        var $this = $(this).parents('.k-form__group');
        var selectVal = $(this).val();
        var $radioBtnBlock = $this.find('.radio-btn-block:first');
        var $radioInputBlock = $this.nextAll('.radio-input-block:first');
        var $checkboxBtnBlock = $this.find('.checkbox-btn-block:first');
        var $checkboxInputBlock =  $this.nextAll('.checkbox-input-block:first');
        switch(selectVal){
            case '1':
            case '4':
                $radioBtnBlock.removeClass('display-block');
                $radioInputBlock.removeClass('display-block');
                $checkboxBtnBlock.removeClass('display-block');
                $checkboxInputBlock.removeClass('display-block');
                break;
            case '2':
                $radioBtnBlock.addClass('display-block');
                $radioInputBlock.addClass('display-block');
                $checkboxBtnBlock.removeClass('display-block');
                $checkboxInputBlock.removeClass('display-block');
                break;
            case '3':
                $radioBtnBlock.removeClass('display-block');
                $radioInputBlock.removeClass('display-block');
                $checkboxBtnBlock.addClass('display-block');
                $checkboxInputBlock.addClass('display-block');
                break;
        }
    }

    function addCheckboxInput() {
        var $step = $(this).parents('.step:first');
        var $checkboxInputBlock =  $step.find('.checkbox-input-block:first');
        var levelCode = $checkboxInputBlock.parents('.step:first').data('levelCode');
        var index = $checkboxInputBlock.children().length + 1;
        var checkBoxInputId = 'checkName-' + levelCode + '-' + index;
        var checkBoxStr = `<div class="col-md-12 col-lg-6 col-xl-4 clearfix">
                                <div class="k-form__item required" title="复选框名称">
                                    <label class="k-form__item-label">复选框名称:</label>
                                    <div class="k-form__item-content">
                                        <div class="k-input-icon k-input-icon--right">
                                            <input type="text" id="`+ checkBoxInputId +`" name="checkName" class="form-control check-input">
                                            <span class="k-input-icon__icon k-input-icon__icon--right">
                                                            <span><i class="fa fa-times-circle"></i></span>
                                                        </span>
                                        </div>
                                    </div>
                                </div>
                            </div>`;
        $checkboxInputBlock.append($(checkBoxStr));
    }

    function addRadioInput() {
        var $step = $(this).parents('.step:first');
        var $radioBtnBlock =  $step.find('.radio-input-block:first');
        var levelCode = $radioBtnBlock.parents('.step:first').data('levelCode');
        var index = $radioBtnBlock.children().length + 1;
        var radioInputId = 'radioName-' + levelCode + '-' + index;
        var radioStr = `<div class="col-md-12 col-lg-6 col-xl-4 clearfix">
                            <div class="k-form__item required" title="单选框名称">
                                <label class="k-form__item-label">单选框名称:</label>
                                <div class="k-form__item-content">
                                    <div class="k-input-icon k-input-icon--right">
                                        <input type="text" id="`+ radioInputId +`" name="radioName" class="form-control radio-input">
                                        <span class="k-input-icon__icon k-input-icon__icon--right">
                                            <span><i class="fa fa-times-circle"></i></span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>`;
        $radioBtnBlock.append($(radioStr));
    }

    /**
     * 初始化已选择的数据集
     */
    function initSelectNodes() {
        var $relatedTarget = $('#select-dataSet').data('$relatedTarget');
        if (!$relatedTarget) {
            return false;
        }
        var $input = $relatedTarget.parent().siblings('input[type="hidden"]');
        var selectNodeId = $input.val();
        if (!selectNodeId) {
            return false;
        }

        var zTreeObj = $.fn.zTree.getZTreeObj('dataSet-tree');

        var dataSetIds = selectNodeId.split(',');
        dataSetIds.forEach(function (id) {
            var treeNode = zTreeObj.getNodeByParam("id", id, null);
            zTreeObj.checkNode(treeNode, true, true);
        });
    }
    //*****数据项配置--结束*****//

    return {
        // public functions
        init: function($table, options) {
            if (options.editable !== false) {
                eventHandler();
            }

            configTableId = $table.attr('id');
            initConfigTable($table, options);
        },
        initSelectNodes: initSelectNodes,
        appendDataSet: appendDataSet,
        getConfigData: getConfigData
    };
}();